﻿using Halcon二次开发.Controller.多模板匹配;
using Halcon二次开发.Model.自定义控件;
using Halcon二次开发.Tools;
using Halcon二次开发.View.多模板匹配;
using Halcon二次开发.View.精准测量模块;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.WebSockets;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Xml.Linq;
using 可视化工具.Controller.Csv文件交互;
using static System.Windows.Forms.AxHost;
using System.Xml.Serialization;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows.Input;
using Halcon二次开发.Controller.CamerForm交互;

namespace 可视化工具.View.Csv文件
{
    public partial class CsvMainForm : Form
    {
        /// <summary>
        /// 任务文件的全路径
        /// </summary>
        public string fullPath;
        public CsvController controller;
        public HwindowFlowNodeUrseControl hwindowFlowNodeUrseControl;
        public string name;
        /// <summary>
        /// csv文件的配置文件，包含了文件名和所有列
        /// </summary>
        public CsvConfig csvConfig;

        public string FullPath
        {
            get => fullPath;
            set
            {
                fullPath = value;
                路径label.Text = value;
            }
        }

        public CsvMainForm()
        {
            InitializeComponent();
            
        }

        public CsvMainForm(HwindowFlowNodeUrseControl hwindowFlowNodeUrseControl, string fullPath, string name) : this()
        {
            try
            {
                controller = new CsvController(this);
                this.MinimizeBox = false;
                this.name = name;
                this.hwindowFlowNodeUrseControl = hwindowFlowNodeUrseControl;
                this.FullPath = fullPath;
                ReadCsvConfig();
                //将首行重置—将列重置
                controller.ReFlushColumns();
            }
            catch
            {
                // MessageBox.Show("CsvMainForm");
            }
        }
        /// <summary>
        /// 初始化配置
        /// </summary>
        public void ReadCsvConfig()
        {
            //读取序列化后的数据
            if (!Directory.Exists(FullPath + "\\csv文件"))
            {
                Directory.CreateDirectory(FullPath + "\\csv文件");
            }
            //以下最重要
            //string formattedTime = DateTime.Now.ToString("yyyy_MM_dd_HH_mm");
            string formattedTime = DateTime.Now.ToString("yyyy_MM_dd");
            string fullPath = Path.Combine(FullPath + "\\csv文件", $"{this.name + "_" + formattedTime}.csv");

            //配置文件
            if (!File.Exists(FullPath + "\\csv配置文件.json"))
            {
                using (File.Create(FullPath + "\\csv配置文件.json")) { }
                csvConfig = new CsvConfig();
                controller.SerializeToIni(csvConfig, FullPath + "\\csv配置文件.json");
            }
            else
            {
                csvConfig = controller.DeserializeFromIni(FullPath + "\\csv配置文件.json");
                
            }
            csvConfig.controller = this.controller;
            controller.csvFilePath = fullPath; 
            uiTextBox1.Text = this.name + "_" + formattedTime;
        }
        /// <summary>
        /// 关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CsvMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Hide();
            e.Cancel = true;
        }
        /// <summary>
        /// 打开文件按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void toolStripButton1_Click(object sender, EventArgs e)
        {
            // 禁用按钮，防止重复点击
            toolStripButton1.Enabled = false;
            try
            {
                // 显示确认框
                DialogResult result = MessageBox.Show(
                    "请确保当前软件在非运行状态 您确定要执行此操作吗？",
                    "确认操作",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question
                );

                if (result == DialogResult.Yes)
                {
                    bool paper = false;
                    if (hwindowFlowNodeUrseControl?.camerFormController != null)
                    {
                        if (hwindowFlowNodeUrseControl.camerFormController.triggerModePaper && hwindowFlowNodeUrseControl.camerFormController.triggerSourcePaper && hwindowFlowNodeUrseControl.runPaper)
                        {
                            paper = true;
                            MessageBox.Show("软件正在运行状态！ 请点击左侧菜单停止按钮以正确执行该操作", "无法操作", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    if (!paper)
                    {
                        try
                        {
                            // 检查文件是否存在
                            if (System.IO.File.Exists(controller.csvFilePath))
                            {
                                // 使用默认应用程序打开文件（例如 Excel 或其他 CSV 查看工具）
                                Process.Start(new ProcessStartInfo(controller.csvFilePath) { UseShellExecute = true });
                            }
                            else
                            {
                                MessageBox.Show("文件不存在！ 该文件已新建");
                                controller.ReFlushColumns();
                                toolStripButton1_Click(sender, e);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"无法打开文件: {ex.Message}");
                        }; // 执行确认操作
                    }
                }
            }
            finally
            {
                // 对话框关闭后，重新启用按钮
                toolStripButton1.Enabled = true;
            }
        }
        /// <summary>
        /// 打开文件路径按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void toolStripButton2_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取文件所在的目录
                string directoryPath = System.IO.Path.GetDirectoryName(controller.csvFilePath);

                // 打开文件夹资源管理器
                Process.Start("explorer.exe", directoryPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法打开文件: {ex.Message}");
            }
        }
        /// <summary>
        /// 另存为按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            // 创建 SaveFileDialog 实例
            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                // 设置默认文件类型和文件扩展名
                saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
                saveFileDialog.Title = "另存为 CSV 文件";

                // 显示对话框并检查用户是否选择了保存位置
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取用户选择的目标文件路径
                    string targetFilePath = saveFileDialog.FileName;

                    try
                    {
                        // 检查原文件是否存在
                        if (File.Exists(controller.csvFilePath))
                        {
                            // 将原文件内容复制到新文件
                            File.Copy(controller.csvFilePath, targetFilePath, true); // true 表示如果目标文件已存在，将覆盖它

                            MessageBox.Show($"文件已成功另存为: {targetFilePath}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show("原始文件不存在！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        public void Form_AddPage(Form form, string name, TreeNode headNode)
        {
            try
            {
                TabPage tabPage = new TabPage();
                //绑定对应的treenode节点
                tabPage.Tag = headNode;

                tabPage.Text = name;
                tabPage.Name = name;

                form.TopLevel = false;
                form.Parent = tabPage;
                form.Dock = DockStyle.Fill;

                tabPage.Controls.Add(form);
                uiTabControlMenu1.TabPages.Add(tabPage);
                form.Show();
                //tabpage页文本发生改变的事件 当text文本改变时，节点同步更改名称和文本
                tabPage.TextChanged += TabPage_TextChanged;

                if (form is CsvModelForm csvModel)
                {
                  
                    if (csvConfig.modelName!=string.Empty&&csvConfig.modelName.Contains("_@#"))
                    {
                        headNode.Text = Regex.Replace(csvConfig.modelName, "_@#", "");
                        csvModel.checkBox1.Tag = "1";
                        csvModel.checkBox1.Checked = false;
                        csvModel.checkBox1.Tag = "0";
                    }
                    else
                    {
                        csvConfig.modelName = headNode.Text;
                        controller.SerializeToIni(csvConfig, FullPath + "\\csv配置文件.json");
                        //往tab页插入列
                        controller.AddNewColumnAsync(new List<string>() { headNode.Text });
                    }
                    csvModel.textBox模板.Text = headNode.Text.Substring(7);
                    

                }
                else if (form is CsvCailperForm_ csvCailperForm_)
                {
                    if (csvConfig.cailpeVlues.ContainsKey(headNode.Text))
                    {
                        List<string> names = csvConfig.cailpeVlues[headNode.Text];
                        // 如果模块工具名称相同，则将 vlaue 拿到
                        csvCailperForm_.textBox模块工具.Text = headNode.Text.Substring(6);
                        List<string> namesTwo = new List<string>();
                        // 定义对应控件的映射
                        var controls = new[]
                        {
                            new { CheckBox = csvCailperForm_.checkBox卡尺, TextBox = csvCailperForm_.textBox卡尺 },
                            new { CheckBox = csvCailperForm_.checkBox距离转换, TextBox = csvCailperForm_.textBox距离转换 },
                            new { CheckBox = csvCailperForm_.checkBox结果分析, TextBox = csvCailperForm_.textBox结果分析 },
                            new { CheckBox = csvCailperForm_.checkBox间距, TextBox = csvCailperForm_.textBox间距 },
                        };
                        for (int i = 0; i < names.Count; i++)
                        {
                            if (names[i].Contains("_@#"))
                            {
                                // 去掉"_@#"后设置 TextBox 值;
                                controls[i].CheckBox.Tag = "1";
                                controls[i].CheckBox.Checked = false;
                                controls[i].CheckBox.Tag = "0";
                                controls[i].TextBox.Text = Regex.Replace(names[i], "_@#", "");
                            }
                            else
                            {
                                // 添加到 namesTwo 并设置 TextBox 值
                                namesTwo.Add(headNode.Text + "." + names[i]);
                                controls[i].TextBox.Text = names[i];
                            }
                        }
                        // 异步调用添加新列的方法
                        controller.AddNewColumnAsync(namesTwo);
                    }
                    else
                    {
                        csvConfig.cailpeVlues.Add(headNode.Text, new List<string>()
                        {
                            "value1_@#","value2","value3","value4_@#"
                        });

                        csvCailperForm_.textBox模块工具.Text = headNode.Text.Substring(6);
                        controller.AddNewColumnAsync(new List<string>() {
                                headNode.Text+".value2",
                                headNode.Text+".value3",
                            });
                        //controller.AddNewColumnAsync(new List<string>() {
                        //        headNode.Text+".value1_@#",
                        //        headNode.Text+".value2",
                        //        headNode.Text+".value3",
                        //        headNode.Text+".value4_@#",
                        //    });
                        controller.SerializeToIni(csvConfig, FullPath + "\\csv配置文件.json");
                    }
                }
            }
            catch (Exception ex)
            {
                //  MessageBox.Show("无法在csv文件打开的情况下添加工具 ", "添加错误");
            }

        }
        /// <summary>
        /// pag页改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabPage_TextChanged(object sender, EventArgs e)
        {
            if (sender is TabPage childPags)
            {
                if (childPags.Tag is TreeNode headNode)
                {
                    headNode.Name = childPags.Text;
                    headNode.Text = childPags.Text;

                    if (headNode.Tag is H_PMA_S_AlignToolForm h_PMA_S_AlignToolForm)
                    {
                        h_PMA_S_AlignToolForm.Text = headNode.Text;
                        h_PMA_S_AlignToolForm.Name = headNode.Name;

                        // pmaForm.filePath
                        //将shm文件更名
                       //string i= h_PMA_S_AlignToolForm.filePath;
                         System.IO.File.Move( h_PMA_S_AlignToolForm.filePath, System.IO.Path.Combine(System.IO.Path.GetDirectoryName(h_PMA_S_AlignToolForm.filePath), h_PMA_S_AlignToolForm.Name)+"工位模板.shm");
                        h_PMA_S_AlignToolForm.filePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(h_PMA_S_AlignToolForm.filePath),h_PMA_S_AlignToolForm.Name) + "工位模板.shm";


                    }
                    else if (headNode.Tag is CaliperModuleForm caliperModuleForm)
                    {
                        string pathOld = $@"Data\工程文件\{caliperModuleForm.controller.hwindowFlowNode.projectName}\{caliperModuleForm.controller.hwindowFlowNode.name}任务文件\精准测量工具卡尺校验数据\{caliperModuleForm.caliperForm.nodeName}";

                        caliperModuleForm.Text = headNode.Text;
                        caliperModuleForm.Name = headNode.Name;
                        caliperModuleForm.caliperForm.nodeName=headNode.Name;

                        string pathNew = $@"Data\工程文件\{caliperModuleForm.controller.hwindowFlowNode.projectName}\{caliperModuleForm.controller.hwindowFlowNode.name}任务文件\精准测量工具卡尺校验数据\{caliperModuleForm.caliperForm.nodeName}";

                        System.IO.Directory.Move(pathOld, pathNew);
                       
                    }
                }
            }
        }

        public async void Form_RemovePage(string name)
        {
            try
            {
                int index = -1;
                TabPage tab = null;
                for (int i = 0; i < uiTabControlMenu1.TabPages.Count; i++)
                {
                    if (name == uiTabControlMenu1.TabPages[i].Name)
                    {
                        tab = uiTabControlMenu1.TabPages[i];
                        index = i;
                        break;
                    }
                }
                if (tab != null)
                {
                    if (tab.Text.Contains("多目标模型"))
                    {
                        //彻底删除
                       
                        try
                        {
                            // await controller.RemoveColumnsAsync(1, 1);
                         await controller.RemoveColumnsAsync(name);
                        }
                        catch
                        {

                        }
                        csvConfig.modelName = string.Empty;
                    }
                    else if (tab.Text.Contains("测量模块"))
                    {
                        try
                        {
                            // await controller.RemoveColumnsAsync(1, 1);
                            await controller.RemoveColumnsAsync(name);
                        }
                        catch
                        {

                        }
                        csvConfig.cailpeVlues.Remove(tab.Text);
                    }
                    controller.SerializeToIni(csvConfig, FullPath + "\\csv配置文件.json");
                    uiTabControlMenu1.TabPages.Remove(tab);

                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("该文件"))
                {
                    MessageBox.Show("无法在csv文件打开的情况下删除该工具", "错误");
                }
                else
                {
                    // MessageBox.Show("删除"ex.Message);
                }

            }
        }
        public bool CsvModelFormNameChanged(string name)
        {
            return controller.TabPageNameChanged(name);
        }

    }
    

}
